<?php

namespace app\common\cachemodel\zl4;

use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl4HoroscopeGoodTime extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl4_horoscope_good_time';

    protected $cacheModel = 'horoscope.good_time_report';

    /**
     * 写入数据
     * @return bool
     */
    public function SaveData(int $uid, array $data)
    {
        try
        {
//            $data = [
//                'uid' => 1,
//                'hash' => '',
//                'rid1' => 1,
//                'rid2' => 1,
//                'tid' => 1,
//                'status' => 2,  // 直接计算成功
//                'order_num' => '',
//                'start_date' => 1672675200,
//                'end_date' => 1673193600,
//                'day_num' => 2,   解锁日期内 的吉日天数
//                'unlock_day_num' => 7,
//                'unlock_days' => [[1672675200, 1673193600]],
//                'content' => '',
//                'recode_info' => ['recode1' => {}],
//                'create_time' => time(),
//                'end_time' => time(),
//            ];
            $id = $this->insertGetId($data);
            // 添加解锁列表记录
            $this->listDataAdd($uid, [$id => $id]);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('user_unlock_tags', $uid)->rmCache('user_unlock_tags');
            // 删除 解锁日期信息
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('user_unlock_days', $uid)->rmCache('user_unlock_days');
            // 添加 吉日吉时 解锁记录小红点
            (new Zl4HoroscopeGoodTimeIsNew())->setNewStatus($uid, 1);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeGoodTime model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return true;
        }
    }

    /**
     * 更新报告数据
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data): bool
    {
        try
        {
            $this->where('id', $id)->update($data);
            // 删除缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeGoodTime model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {   // 获取未删除 的数据
                $data = $this
                    ->where(['id' => ['in', $ids]])
                    ->column('id,uid,hash,rid1,rid2,tid,status,order_num,start_date,end_date,unlock_day_num,unlock_days,content,recode_info,extend,create_time,end_time,day_num', 'id');
            } else
            {
                $data = $this->where(['uid' => $type[0]])->order('id desc')->column('id,uid,hash,rid1,rid2,tid,status,order_num,start_date,end_date,unlock_day_num,unlock_days,content,recode_info,extend,create_time,end_time,day_num', 'id');
            }
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'rid1', 'rid2', 'tid', 'status', 'start_date', 'end_date', 'unlock_day_num', 'day_num', 'end_time', 'create_time']);

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }

            if (isset($itemData['unlock_days']))
            {
                $data[$index]['unlock_days'] = $itemData['unlock_days'] ? json_decode($itemData['unlock_days'], true) : [];
            }

            if (isset($itemData['content']))
            {
                $data[$index]['content'] = $itemData['content'] ? json_decode($itemData['content'], true) : [];
            }

            if (isset($itemData['recode_info']))
            {
                $data[$index]['recode_info'] = $itemData['recode_info'] ? json_decode($itemData['recode_info'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 获取用户解锁 日期
     * @param int $uid
     * @param string $unlockHashKey
     * @return array
     * @throws \Exception
     */
    public function getUserUnlockDates(int $uid, string $unlockHashKey = '')
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheKeyDetail('user_unlock_days', $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->where(['uid' => $uid])->column('rid1,rid2,tid,hash,start_date,end_date', 'id');

                $resData = [];
                foreach ($data as $id => $datum)
                {
                    $key = "{$datum['rid1']}:{$datum['rid2']}:{$datum['hash']}:{$datum['tid']}";
                    $resData[$key][] = [$datum['start_date'], $datum['end_date']];
                }

                foreach ($resData as $keyItem => $dataItem)
                {
                    $resData[$keyItem] = json_encode($dataItem, JSON_UNESCAPED_UNICODE);
                }

                return $resData;
            }
            catch (\Exception $e)
            {
                Log::write('Zl4HoroscopeGoodTime model => getUserUnlockDates()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                return [];
            }
        }, [], 'user_unlock_days');

        if ($unlockHashKey)
        {
            if (isset($data[$unlockHashKey]))
            {
                $unlockDateInfo = json_decode($data[$unlockHashKey], true);

                $unlockDates = [];
                foreach ($unlockDateInfo as $itemData)
                {
                    $d = $itemData[0];
                    do
                    {
                        $unlockDates[] = date('Y-m-d', $d);
                        $d += 86400;
                    } while ($d <= $itemData[1]);
                }

                return [$unlockHashKey => array_unique($unlockDates)];
            } else
            {
                return [$unlockHashKey => []];
            }
        } else
        {
            $resData = [];
            foreach ($data as $k => $v)
            {
                $unlockDateInfo = json_decode($v, true);
                $unlockDates = [];
                foreach ($unlockDateInfo as $itemData)
                {
                    $d = $itemData[0];
                    do
                    {
                        $unlockDates[] = date('Y-m-d', $d);
                        $d += 86400;
                    } while ($d <= $itemData[1]);
                }
                $resData[$k] = array_unique($unlockDates);
            }

            return $resData;
        }
    }

    /**
     * 获取 用户 八字 吉日吉时 记录
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getLists(int $uid)
    {
        $pageData = $this->getListPage($uid, 'id', ['id', 'tid', 'start_date', 'end_date', 'day_num', 'unlock_day_num']);

        $pageData['data'] = $this->dataInit($pageData['data']);

        $tids = $pageData['data'] ? array_values(array_unique(array_column($pageData['data'], 'tid'))) : [];

        $tagInfo = $tids ? (new Zl4GoodTimeTag())->batchGetInfoByIds($tids, ['name']) : [];

        $resData = [];
        foreach ($pageData['data'] as $datum)
        {
            $resData[] = [
                'id' => $datum['id'],
                'title' => "适宜{$tagInfo[$datum['tid']]['name']}的日子",
                'des' => sprintf("%s 至 %s（共解锁%d天）", date('Y-m-d', $datum['start_date']), date('Y-m-d', $datum['end_date']), $datum['unlock_day_num']),
                'day_num' => $datum['day_num'],
            ];
        }
        $pageData['data'] = $resData;

        return $pageData;
    }

    /**
     *  获取用户解锁 事项 ID 信息
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getUnlockTags(int $uid)
    {
        $resData = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('user_unlock_tags', $uid)
            ->setCacheType('string')->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $data = $this->where('uid', $uid)->order('id desc')->column('tid', 'id');

                    $resData = [];
                    foreach ($data as $id => $tid)
                    {
                        if (!isset($resData[$tid]))
                        {
                            $resData[$tid] = $id;
                        }
                    }

                    return json_encode($resData, JSON_UNESCAPED_UNICODE);
                }
                catch (\Exception $e)
                {
                    Log::write('Zl4HoroscopeGoodTime model => getUnlockTags()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                    return '';
                }
            }, [], 'user_unlock_tags');

        return $resData ? json_decode($resData, true) : [];
    }
}
